package com.jblog.controller.directive;

import static com.jblog.Constants.Encoding.UTF8;
import static com.jblog.Constants.Template.TPL_STYLE_LIST;
import static com.jblog.Constants.Template.TPL_SUFFIX;
import static com.jblog.common.web.freemarker.DirectiveUtils.OUT_LIST;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.jblog.common.web.FrontUtils;
import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.core.model.blog.Tag;
import com.jblog.core.model.blog.param.TagParam;
import com.jblog.core.model.common.Status;
import com.jblog.core.service.facde.BlogFacade;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@SuppressWarnings({"unchecked", "rawtypes"})
public class TagListDirective implements TemplateDirectiveModel{
    
    @Autowired protected BlogFacade iblog;
    
    public static final String PARAM_POST_ID     =  "postId";
    public static final String PARAM_TAG_STATUS  =  "tagStatus";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        List<Tag> list = getList(params, env);
        
        Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
        paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
        Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);

        env.include(TPL_STYLE_LIST + DirectiveUtils.getStyleList(params) + TPL_SUFFIX, UTF8, true);
        
        DirectiveUtils.removeParamsFromVariable(env, params, origMap);
    }

    private Long postId(Map<String, TemplateModel> params) throws TemplateException {
        return DirectiveUtils.getLong(PARAM_POST_ID, params);
    }
    private Status tagStatus(Map<String, TemplateModel> params) throws TemplateException {
        String s = DirectiveUtils.getString(PARAM_TAG_STATUS, params); 
        return null == s ? null : Status.valueOf(s.toUpperCase());
    }
    
    public List<Tag> getList(Map<String, TemplateModel> params,
            Environment env) throws TemplateException {
        TagParam tagParam = null;
        
        if (null != postId(params)) {
            return iblog.findTagByPostId(postId(params));
        } else {
            tagParam = new TagParam(FrontUtils.first(params), FrontUtils.count(params));
            tagParam.setStatus(tagStatus(params));
            return iblog.findTagByParamByPage(tagParam);
        }
    }
    
}
